package services;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.BitmapFactory;
import android.os.Binder;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import android.util.Log;

import com.baidu.mapapi.SDKInitializer;
import com.baidu.trace.LBSTraceClient;
import com.baidu.trace.Trace;
import com.baidu.trace.api.entity.AddEntityRequest;
import com.baidu.trace.api.entity.AddEntityResponse;
import com.baidu.trace.api.entity.AroundSearchResponse;
import com.baidu.trace.api.entity.BoundSearchResponse;
import com.baidu.trace.api.entity.DeleteEntityResponse;
import com.baidu.trace.api.entity.DistrictSearchResponse;
import com.baidu.trace.api.entity.EntityListResponse;
import com.baidu.trace.api.entity.OnEntityListener;
import com.baidu.trace.api.entity.PolygonSearchResponse;
import com.baidu.trace.api.entity.SearchResponse;
import com.baidu.trace.api.entity.UpdateEntityResponse;
import com.baidu.trace.model.LocationMode;
import com.baidu.trace.model.OnTraceListener;
import com.baidu.trace.model.ProtocolType;
import com.baidu.trace.model.PushMessage;
import com.baidu.trace.model.TraceLocation;
import com.utra.hellshan.upload.Broadcast.NetworkReceiver;
import com.utra.hellshan.upload.OtherTools.SystemUtil;
import com.utra.hellshan.upload.R;
import com.utra.hellshan.upload.UI.mapAvtivity;

//import com.baidu.trace.model.OnTraceListener;

public class TrackService extends Service {
    /**
     *
     * 本服务为真正的轨迹服务。
     *
     *
     */


    private int enityNumber = 0 ;                   //周围的实例数量
    private int currentSpeed = 0 ;                  //当前设备的速度

    private  Trace trace ;
    public  LBSTraceClient client;
    private  OnEntityListener onEntityListener;
    private  AddEntityRequest addEntityRequest;
    private  OnTraceListener traceListener;

    NetworkReceiver networkReceiver;

    AddedEntity addedEntity ;
    startedGuide  mstartedGuide ;
    startedTrace  mstartedTrace ;



    @Override
    public void onCreate() {
        super.onCreate();



        addedEntity = new AddedEntity();
        mstartedGuide = new startedGuide();
        mstartedTrace = new startedTrace();

        SDKInitializer.initialize(getApplicationContext());
        Log.d("1" ,"轨迹服务创建成功");



        /*
        注册广播接收器，没啥用，没找到正确打开方式
         */
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");

        registerReceiver(networkReceiver,intentFilter);






        IntentFilter intentFilter_addentity ;   //用于注册接收Addentity成功的广播
        intentFilter_addentity = new IntentFilter();
        intentFilter_addentity.addAction("mybroadcast.trackservice.addedentity");
        registerReceiver(addedEntity , intentFilter_addentity);


        IntentFilter intentFilter_startedTrace ;   //用于注册接收开启服务成功的广播
        intentFilter_startedTrace = new IntentFilter();
        intentFilter_startedTrace.addAction("mybroadcast.trackservice.startedTrace");
        registerReceiver(mstartedTrace, intentFilter_startedTrace);


        IntentFilter intentFilter_startedGuide ;   //用于注册接收开启daohang成功的广播
        intentFilter_startedGuide = new IntentFilter();
        intentFilter_startedGuide.addAction("mybroadcast.trackservice.startedGuide");
        this.registerReceiver(mstartedGuide, intentFilter_startedGuide);

        networkReceiver = new NetworkReceiver();

        //初始化traceListener
        traceListener = new OnTraceListener() {
            @Override
            public void onBindServiceCallback(int i, String s) {
                Log.d("Ontrace Lintener" ,"服务绑定，状态码" + i + " , 信息：" + s + "\n");

            }


            @Override
            public void onStartTraceCallback(int i, String s) {

                if(i != 0 && i!=10006 && i!= 10005)
                {
                    client.startTrace(trace,traceListener);
                }
                else
                {
                    Intent intent_ = new Intent("mybroadcast.trackservice.startedTrace");
                    sendBroadcast(intent_);
                }

                Log.d("Ontrace Lintener" ,"StartTrace，状态码" + i + " , 信息：" + s + "\n");
            }

            @Override
            public void onStopTraceCallback(int i, String s) {
            }

            @Override
            public void onStartGatherCallback(int i, String s) {
                Log.d("Ontrace Lintener" ,"Start Gather info code: " + i + ",info : " + s + "\n");
                if(i != 0 && i!=12003)
                {
                    client.startGather(traceListener);
                }
                else
                {
                    Intent intent_ = new Intent("mybroadcast.trackservice.startedGuide");
                    sendBroadcast(intent_);
                }
            }

            @Override
            public void onStopGatherCallback(int i, String s) {
            }

            @Override
            public void onPushCallback(byte b, PushMessage pushMessage) {
                Log.d("Ontrace Lintener" ,"Message fron Server:" + pushMessage.getMessage() + "\n");
            }

            @Override
            public void onInitBOSCallback(int i, String s) {
            }
        };
        onEntityListener = new OnEntityListener() {
            @Override
            public void onAddEntityCallback(AddEntityResponse addEntityResponse) {
                Log.d("AddEnity","AddEnity Message: " + addEntityResponse.status + addEntityResponse.message + "\n");
                if(addEntityResponse.status == 14004 )
                    client.addEntity(addEntityRequest , onEntityListener);
                else
                {
                    Intent intent_ = new Intent("mybroadcast.trackservice.addedentity");
                    Log.d("1" , "added entity , broading nroadcast");
                    sendBroadcast(intent_);
                }
                super.onAddEntityCallback(addEntityResponse);
            }

            @Override
            public void onUpdateEntityCallback(UpdateEntityResponse updateEntityResponse) {
                Log.d("AddEnity","++++ Enity-update-request send ++++\n");
                super.onUpdateEntityCallback(updateEntityResponse);
            }

            @Override
            public void onDeleteEntityCallback(DeleteEntityResponse deleteEntityResponse) {
                super.onDeleteEntityCallback(deleteEntityResponse);
            }

            @Override
            public void onEntityListCallback(EntityListResponse entityListResponse) {
                super.onEntityListCallback(entityListResponse);
            }

            @Override
            public void onSearchEntityCallback(SearchResponse searchResponse) {
                super.onSearchEntityCallback(searchResponse);
            }

            @Override
            public void onBoundSearchCallback(BoundSearchResponse boundSearchResponse) {
                super.onBoundSearchCallback(boundSearchResponse);
            }

            @Override
            public void onAroundSearchCallback(AroundSearchResponse aroundSearchResponse) {
                super.onAroundSearchCallback(aroundSearchResponse);
            }

            @Override
            public void onPolygonSearchCallback(PolygonSearchResponse polygonSearchResponse) {
                super.onPolygonSearchCallback(polygonSearchResponse);
            }

            @Override
            public void onDistrictSearchCallback(DistrictSearchResponse districtSearchResponse) {
                super.onDistrictSearchCallback(districtSearchResponse);
            }

            @Override
            public void onReceiveLocation(TraceLocation traceLocation) {
                super.onReceiveLocation(traceLocation);
            }
        };
        client = new LBSTraceClient(this.getApplicationContext());
        addEntityRequest = new AddEntityRequest(0,StatusService.getServiceID(), StatusService.getEnityName());
        //trace = new Trace(StatusService.getServiceID(),StatusService.getEnityName(), false, null);

        client.addEntity(addEntityRequest, onEntityListener);
        trace = new Trace(StatusService.getServiceID(),StatusService.getEnityName(), false, null);
        Log.e("11111111111111111111" , "开启服务前获取到的entityname为" + StatusService.getEnityName());




        client.setLocationMode(LocationMode.High_Accuracy); //设置为高精确度定位
        client.setProtocolType(ProtocolType.HTTP);
        client.setInterval(1, 3);//设置采集周期及上传周期







        NotificationManager manager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);

        if(Build.VERSION.SDK_INT >= 26)
        {
            //当sdk版本大于26
            String id = "channel_1";
            String description = "本通知用于后台保活";
            int importance = NotificationManager.IMPORTANCE_LOW;
            NotificationChannel channel = new NotificationChannel(id, description, importance);

            manager.createNotificationChannel(channel);
            Notification notification = new Notification.Builder(getApplicationContext())
                    .setCategory(Notification.CATEGORY_MESSAGE)
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setContentTitle("Notification")
                    .setContentText("正在作为实体 " + StatusService.getEnityName() + "运行中；")
                    .setAutoCancel(true)
                    .setChannelId(id)
                    .build();
            notification.flags |= Notification.FLAG_ONGOING_EVENT;

            manager.notify(1, notification);
        }
        else
        {

            //当sdk版本小于26
            Notification notification = new NotificationCompat.Builder(this)
                    .setContentTitle("Notification")
                    .setContentText("正在作为实体 " + StatusService.getEnityName() + "运行中；")
                    .setWhen(System.currentTimeMillis())
                    .setSmallIcon(R.drawable.ic_launcher_foreground)
                    .setLargeIcon(BitmapFactory.decodeResource(getResources(),R.drawable.ic_launcher_foreground))
                    .build();

            notification.flags |= Notification.FLAG_ONGOING_EVENT;

            manager.notify(1,notification);
        }
    }

    @Nullable


    public void startGather()
    {
        client.startGather(traceListener);
    }

    public void startTrace()
    {
        client.startTrace(trace,traceListener);
    }

    public LBSTraceClient getClient() { return client; }

    public TrackService() { }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return new MyBinder();
    }

    public class MyBinder extends Binder{
        public TrackService getMyService(){
            return TrackService.this;
        }
    }


    public class AddedEntity extends BroadcastReceiver
    {

        @Override
        public void onReceive(Context context, Intent intent) {


            Log.d("1" , "Device assed in recvier");
            client.startTrace(trace,traceListener);

        }
    }

    public class startedTrace extends BroadcastReceiver
    {

        @Override
        public void onReceive(Context context, Intent intent) {

            Log.d("1" , "Trace started in recvier");

            client.startGather(traceListener);

        }
    }

    public class startedGuide extends BroadcastReceiver
    {

        @Override
        public void onReceive(Context context, Intent intent) {


            Log.d("1" , "Gathed started in recvier");

            //发送一个自定义广播，通知其他 本service启动成功
            Intent intent_ = new Intent("mybroadcast.trackservice.start");
            sendBroadcast(intent_);

        }
    }

}
